package com.tubang.logistics.controller.order;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.tubang.common.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.tubang.common.constant.Constants;
import com.tubang.component.entity.AddressEntity;
import com.tubang.component.service.IAddressService;
import com.tubang.component.util.RequestUtil;
import com.tubang.logistics.entity.GoodsEntity;
import com.tubang.logistics.entity.ShipperOrderEntity;
import com.tubang.logistics.entity.TransportEntity;
import com.tubang.logistics.service.IGoodsService;
import com.tubang.logistics.service.IShipperOrderService;
import com.tubang.logistics.service.ITransportService;
import com.tubang.logistics.vo.ChangeStatusVo;
import com.tubang.logistics.vo.GoodsBaseVo;
import com.tubang.logistics.vo.GoodsInfoVo;
import com.tubang.logistics.vo.OrderListVo;
import com.tubang.logistics.vo.OrderSupplyVo;
import com.tubang.logistics.vo.OrderbillInfoVo;

/**
 * <p>
 * 货主运单表 前端控制器
 * </p>
 *
 * @author maxl
 * @since 2017-12-31
 */
@RestController
@RequestMapping("/order")
public class OrderShipperController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private IShipperOrderService shipperOrderService;

    @Resource
    private IGoodsService goodsService;


    @Resource
    private IAddressService addressService;


    @Resource
    private ITransportService transportService;

    /**
     * 新增更新货源列表
     * @param request
     * @return
     */
    @PostMapping(value = "insertOrUpdateSupplyOrder")
    public ResultData insertOrUpdateSupplyOrder(HttpServletRequest request) {
        //获取数据
        String receivePostJson = RequestUtil.receivePostJson(request);
        OrderSupplyVo supplyOrderVo = GsonQuick.toObjectDate(receivePostJson, OrderSupplyVo.class);
        logger.info("method发布货源:[insertOrUpdateSupplyOrder]supplyOrderVo=========={}",GsonQuick.getGson().toJson(supplyOrderVo));
        try {
            if(supplyOrderVo==null){
                return ResultData.result(false);
            }
            long now = System.currentTimeMillis();

            //保存订单
            ShipperOrderEntity order = supplyOrderVo.getOrder();
            order.setUpdateTime(new Date(now));
            order.setStatusCode(String.valueOf(Constants.ORDER_STATUS_CODE_PENDING));
            order.setStatusCodeDesc("待接单");
            order.setNum(IdGenerator.INSTANCE.nextId());
            order.setInvoiceFlag(Constants.DEFAULT_VAULE_ZERO);


            shipperOrderService.insertOrUpdate(order);
            //保存运输详情
            TransportEntity transport = supplyOrderVo.getTransport();
            transport.setUpdateTime(new Date(now));
            transport.setOrderId(order.getId());
            transportService.insertOrUpdate(transport);

            //保存货物
            GoodsEntity goodsBasic = supplyOrderVo.getGoodsBasic();
            goodsBasic.setParentId(Constants.DEFAULT_VAULE_ZERO);
            goodsBasic.setUpdateTime(new Date(now));
            goodsBasic.setShipperOrderId(order.getId());
            goodsBasic.setTransportId(transport.getId());
            goodsBasic.setGoodsStatus(Constants.DEFAULT_VAULE_FU_ONE);
            goodsService.insertOrUpdate(goodsBasic);
            List<GoodsEntity> goods = supplyOrderVo.getGoods();
            //goods总吨数
            BigDecimal goodWeight = new BigDecimal(0);
            for (GoodsEntity good : goods) {
                good.setUpdateTime(new Date(now));
                good.setParentId(goodsBasic.getId());
                good.setShipperOrderId(order.getId());
                good.setTransportId(transport.getId());
                good.setGoodsStatus(Constants.DEFAULT_VAULE_FU_ONE);
                goodWeight=goodWeight.add(good.getWeight());
                goodsService.insertOrUpdate(good);
            }
            goodsBasic.setWeight(goodWeight);
            goodsBasic.setLeftWeight(goodWeight);
            order.setGoodsName(goodsBasic.getName());
            order.setCarriageDeal(order.getCarriage());
            order.setAmount(goodWeight.multiply( new BigDecimal(order.getCarriage().doubleValue())).doubleValue());
            order.setAmountDeal(goodWeight.multiply( new BigDecimal(order.getCarriage().doubleValue())).doubleValue());
            order.setGoodsWeight(goodWeight.doubleValue());
            goodsService.insertOrUpdate(goodsBasic);
            //保存收货地址
            //发货人
            StringBuffer addrFrom= new StringBuffer();
            AddressEntity addressFrom = supplyOrderVo.getAddressFrom();
            addressService.insertOrUpdate(addressFrom);
            transport.setFromUserAddressId(addressFrom.getId());
            transport.setFromUserId(addressFrom.getUserId());
            order.setAddrFrom(addrFrom.append(addressFrom.getProvinceName()).append(addressFrom.getCityName()).append(addressFrom.getDistrictName()).toString());
            //收货人
            StringBuffer addrTo=new StringBuffer();
            AddressEntity addresTo = supplyOrderVo.getAddresTo();
            addressService.insertOrUpdate(addresTo);
            transport.setToUserAddressId(addresTo.getId());
            transport.setToUserId(addresTo.getUserId());
            order.setAddrTo(addrTo.append(addresTo.getProvinceName()).append(addresTo.getCityName()).append(addresTo.getDistrictName()).toString());
            transportService.insertOrUpdate(transport);
            shipperOrderService.insertOrUpdate(order);
            logger.info("[OrderShipperController]<== method[insertOrUpdateSupplyOrder],新增或者修改的数据为 ：[{}] ", receivePostJson);
            return ResultData.result(true);
        } catch (Exception e) {
            logger.error("[OrderShipperController]<== method[insertOrUpdateSupplyOrder], 新增或者修改失败 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }

    /**
     * 订单列表 平台货源中心
     * @param
     * @return
     */
    @GetMapping(value = "supplyOrderBillList")
    public ResultData supplyOrderBillList(@RequestParam(required = false) String addrFrom,
                                     @RequestParam(required = false) String addrTo,
                                     @RequestParam(required = false) String num,
                                     @RequestParam(required = false) String statusCode,//98-待审核  99-报价中  100-待接单；101待提货  102-运输中；103-待确认；104已完成；105-异常运单; 106驳回运单
                                          @RequestParam(required = false) String containerType,//车辆类型
                                          @RequestParam(required = false) String containerSize ,//车辆长度
                                          @RequestParam(required = false, defaultValue = "1") Integer page,
                                     @RequestParam(required = false, defaultValue = "10") Integer rows,
                                          @RequestParam(required = false, defaultValue = "") String userId,
                                          @RequestParam(required = false) String companyId,
                                          @RequestParam(required = false) String goodsName) {
        try {
            EntityWrapper<ShipperOrderEntity> entityWrapper=new EntityWrapper<ShipperOrderEntity>();
            if(StringUtils.isNotEmpty(num)){
                entityWrapper.eq("num",num);
            }

           if(StringUtils.isNotEmpty(statusCode)){
                entityWrapper.eq("status_code",statusCode);
            }


            if(StringUtils.isNotEmpty(addrFrom)){
                entityWrapper.like("addr_from",addrFrom);
            }


            if(StringUtils.isNotEmpty(addrTo)){
                entityWrapper.like("addr_to",addrTo);
            }

            if(StringUtils.isNotEmpty(containerType)){
                entityWrapper.eq("container_type",containerType);
            }

            if(StringUtils.isNotEmpty(containerSize)){
                entityWrapper.eq("container_size",containerSize);
            }

            if (StringUtils.isNotEmpty(userId)) {
                entityWrapper.like("user_id", userId);
            }

            if (StringUtils.isNotEmpty(companyId)) {
                entityWrapper.eq("carrier_id", companyId);
            }

            if (StringUtils.isNotEmpty(goodsName)) {
                entityWrapper.eq("goods_name", goodsName);
            }


            Page<ShipperOrderEntity> ShipperOrderPage = shipperOrderService.selectPage(new Page<ShipperOrderEntity>(page, rows), entityWrapper);
            List<ShipperOrderEntity> records = ShipperOrderPage.getRecords();
            List<OrderListVo> orderSupplyListVos = new ArrayList<OrderListVo>();
                    BeanMapper.mapList(records, OrderListVo.class);
            for (ShipperOrderEntity shipperOrderEntity : records) {
                OrderListVo orderListVo=new OrderListVo();
                String orderId = shipperOrderEntity.getId();
                TransportEntity transportEntity = transportService.selectByOrderId(orderId);
                //地址
                if(transportEntity!=null){
                    AddressEntity from = addressService.selectById(transportEntity.getFromUserAddressId());
                    AddressEntity to = addressService.selectById(transportEntity.getToUserAddressId());
                    orderListVo.setAddressFrom(from);
                    orderListVo.setAddresTo(to);
                    BeanMapper.copy(transportEntity, orderListVo);
                    orderListVo.setUnloadPlanDateStr(DateFormatUtils.formatDate(transportEntity.getUnloadPlanDate(), "yyyy-MM-dd HH:mm:ss"));
                    //  orderbillInfoVo.setUnloadRealDateStr(DateFormatUtils.formatDate(transportEtity.getUnloadRealDate(), "yyyy-MM-dd HH:mm:ss"));
                    orderListVo.setTakePlanDateStr(DateFormatUtils.formatDate(transportEntity.getTakePlanDate(), "yyyy-MM-dd HH:mm:ss"));
                    //  orderbillInfoVo.setTakeRealDateStr(DateFormatUtils.formatDate(transportEtity.getTakeRealDate(), "yyyy-MM-dd HH:mm:ss"));
                }
                BeanMapper.copy(shipperOrderEntity, orderListVo);
                orderListVo.setId(orderId);
                orderListVo.setWeight(String.valueOf(shipperOrderEntity.getGoodsWeight()));
                orderSupplyListVos.add(orderListVo);
            }
            int count = shipperOrderService.selectCount(entityWrapper);
            return ResultData.result(true).setData(orderSupplyListVos).setTotalCount(count);
        } catch (Exception e) {
            logger.error("[OrderShipperController]<== method[supplyOrderList], 列表失败 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }



    /**
     * 运单详情
     * @param
     * @return
     */
    @GetMapping(value = "supplyOrderBillInfo")
    public ResultData supplyOrderBillInfo(@RequestParam(required = false) String orderId) {
        try {
            OrderbillInfoVo orderbillInfoVo=new OrderbillInfoVo();
            ShipperOrderEntity order = shipperOrderService.selectById(orderId);
            BeanMapper.copy(order,orderbillInfoVo);
            TransportEntity transportEntity = transportService.selectByOrderId(orderId);
            //地址
            if(transportEntity!=null){
                AddressEntity from = addressService.selectById(transportEntity.getFromUserAddressId());
                AddressEntity to = addressService.selectById(transportEntity.getToUserAddressId());
                orderbillInfoVo.setAddressFrom(from);
                orderbillInfoVo.setAddresTo(to);
                orderbillInfoVo.setTakePlanDate(transportEntity.getTakePlanDate());
                orderbillInfoVo.setTakeRealDate(transportEntity.getTakeRealDate());
                orderbillInfoVo.setUnloadPlanDate(transportEntity.getUnloadPlanDate());
                orderbillInfoVo.setUnloadRealDate(transportEntity.getUnloadRealDate());
                orderbillInfoVo.setUnloadPlanDateStr(DateFormatUtils.formatDate(transportEntity.getUnloadPlanDate(),"yyyy-MM-dd HH:mm:ss"));
                orderbillInfoVo.setUnloadRealDateStr(DateFormatUtils.formatDate(transportEntity.getUnloadRealDate(),"yyyy-MM-dd HH:mm:ss"));
                orderbillInfoVo.setTakePlanDateStr(DateFormatUtils.formatDate(transportEntity.getTakePlanDate(),"yyyy-MM-dd HH:mm:ss"));
                orderbillInfoVo.setTakeRealDateStr(DateFormatUtils.formatDate(transportEntity.getTakeRealDate(),"yyyy-MM-dd HH:mm:ss"));
            }
            BeanMapper.copy(transportEntity,orderbillInfoVo);
            //补充货物明细
            GoodsEntity goodsBasic = goodsService.selectBaseGoodsByOrderId(orderId);
            GoodsBaseVo goodsBaseVo = BeanMapper.map(goodsBasic, GoodsBaseVo.class);
            orderbillInfoVo.setGoodsBaseVo(goodsBaseVo);
            List<GoodsEntity> goodss = goodsService.selectGoodssByOrderId(orderId);
            List<GoodsInfoVo> goodsInfoVos = BeanMapper.mapList(goodss, GoodsInfoVo.class);
            orderbillInfoVo.setGoodsInfoVoS(goodsInfoVos);
            orderbillInfoVo.setAmountDeal(order.getAmountDeal());
            orderbillInfoVo.setCarriageDeal(order.getCarriageDeal());


            return ResultData.result(true).setData(orderbillInfoVo);
        } catch (Exception e) {
            logger.error("[OrderShipperController]<== method[supplyOrderBillInfo], 查询详情 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }


    /**
     *  更新订单状态
     * @param
     * @return
     */
    @PostMapping(value = "updateSupplyOrderStatus")
    public ResultData updateSupplyOrderStatus(HttpServletRequest request) {
        try {
            String receivePostJson = RequestUtil.receivePostJson(request);
            ChangeStatusVo changeStatusVo = GsonQuick.toObject(receivePostJson, ChangeStatusVo.class);
            //更新状态
            shipperOrderService.updateSupplyOrderStatus(changeStatusVo);
            return ResultData.result(true);
        } catch (Exception e) {
            logger.error("[OrderShipperController]<== method[updateSupplyOrderStatus], 更新状态失败 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }


    /**
     *  删除订单
     * @param
     * @return
     */
    @GetMapping(value = "deleteSupplyOrder")
    public ResultData deleteSupplyOrder(@RequestParam String orderId) {
        try {
            //获取数据
            ShipperOrderEntity order = shipperOrderService.selectById(orderId);
            if(order==null) ResultData.result(false).setCode(MsgCode.ORDER_DATA_ERROR).setMsg(MsgCode.ORDER_DATA_ERROR_DESC);
            order.setEnable(false);
            shipperOrderService.insertOrUpdate(order);
            return ResultData.result(true);
        } catch (Exception e) {
            logger.error("[OrderShipperController]<== method[deleteSupplyOrder], 删除失败 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }

}
